package com.yang.refleciton;


import com.yang.entity.User;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author yds
 * @program java-annotation-and-reflection
 * @description 通过反射创建对象
 * @create 2020-10-12 13:55
 **/
public class RefleCore {

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        //获得Class对象

        Class c1 = Class.forName("com.yang.entity.User");
        //构造对象

        //User user= (User)c1.newInstance();//本质上调用无参构造器
        //System.out.println(user);

        //获取构造器->构造对象
        //Constructor constructor = c1.getDeclaredConstructor(String.class, int.class);
        //User user1 =(User) constructor.newInstance("yds", 26);
        //User user2 =(User) constructor.newInstance(null, 0);
        //System.out.println(user1);
        //System.out.println(user2);

        //通过反射调用普通方法
        User user3= (User)c1.newInstance();
        System.out.println(user3);
        Method setName = c1.getMethod("setName", String.class);
        //invoke 激活
        //(对象,对象方法值)
        setName.invoke(user3,"nidaye");
        System.out.println(user3);

        //通过反射操作属性
        User user4= (User)c1.newInstance();
        Field age = c1.getDeclaredField("age");
        //不能操作私有属性,先关闭java的安全检测机制
        age.setAccessible(true);//打开字段的作用域
        age.set(user4,20);
        System.out.println(user4);

    }
}